package board2;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PipedInputStream;
import java.util.StringTokenizer;

import connection.Reader;

public class Style12 extends Board2 implements Runnable {

	Thread cteni = null;
	byte[] buffer = new byte[512];

	int memorya = 0;
	int memoryb = 0;

	int memory2a = 0;
	int memory2b = 0;

	PipedInputStream br;

	BufferedWriter bw;

	private String word = "";

	public Style12() {
		br = Reader.getReader();
		bw = Reader.getWriter();
		Reader.setCtu();
		init();
		cteni = new Thread(this); // (1)
		cteni.start();
	}

	public void writeCom(String com) {
		try {
			bw.write(com);
			bw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void run() { // (2)

		int letter = 0;
		char pom;

		while (true) {

			try {
				letter = br.read();
			} catch (Exception e) {
				e.printStackTrace();
			}
			pom = (char) letter;

			if (letter != 13) {
				word = word.concat(String.valueOf((char) letter));
			}

			if (word.equals("login: ")) {
				writeCom("dovecr\n");
			}

			if (letter == ' ' || letter == 10) {
				// System.out.print(word);
				word = "";
			}

			if (word.equals("<12>")) {
				unsetPressed(memorya, memoryb);
				unsetPressed(memory2a, memory2b);

				for (int a = 0; a < 8; a++) {
					for (int b = 0; b < 8; b++) {
						try {
							letter = br.read();
							if (letter == ' ') {
								letter = br.read();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						pom = (char) letter;
						setPosition(b, a, String.valueOf(pom));
					}
				}
				word = "";
				while (letter != 13) {
					try {
						letter = br.read();
					} catch (Exception e) {
						e.printStackTrace();
					}
					word = word.concat(String.valueOf((char) letter));
				}
				StringTokenizer token = new StringTokenizer(word);
				int q = 0;
				System.out.println(word);
				System.out.println(token.countTokens());

				while (q < 18) {
					token.nextToken();
					q++;
				}
				String move = token.nextToken();
				System.out.println("token:" + move);
				if (!move.substring(0, 1).equals("o") && !move.equals("none")) {
					setPressed(convertLetToNum.get(move.substring(2, 3)),
							Integer.valueOf(move.substring(3, 4)) - 1);

					memorya = convertLetToNum.get(move.substring(2, 3));
					memoryb = Integer.valueOf(move.substring(3, 4)) - 1;
				}
				if (!move.substring(0, 1).equals("o") && !move.equals("none")) {
					setPressed(convertLetToNum.get(move.substring(5, 6)),
							Integer.valueOf(move.substring(6, 7)) - 1);

					memory2a = convertLetToNum.get(move.substring(5, 6));
					memory2b = Integer.valueOf(move.substring(6, 7)) - 1;
				}
			}
		}
	}
}
